package com.feicheng.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.sym.Name;
import com.feicheng.common.constant.Constant;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.common.util.StringGenerator;
import com.feicheng.persistence.entity.Emp;
import com.feicheng.persistence.entity.EmpDept;
import com.feicheng.persistence.entity.FlowRecord;
import com.feicheng.persistence.entity.Job;
import com.feicheng.persistence.entity.Step;
import com.feicheng.persistence.entity.StepRecord;
import com.feicheng.persistence.entity.User;
import com.feicheng.persistence.mapper.EmpDeptMapper;
import com.feicheng.persistence.mapper.EmpMapper;
import com.feicheng.persistence.model.EmpDeptModel;
import com.feicheng.persistence.model.EmpModel;
import com.feicheng.persistence.model.UserModel;
import com.feicheng.persistence.mapper.EmpMapper;
import com.feicheng.persistence.service.*;

import org.aspectj.weaver.bcel.BcelAccessForInlineMunger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
public class FEmpServiceImpl {

	@Autowired
	IUserService iUserService;

	@Autowired
	IEmpService iEmpService;

	@Autowired
	IEmpDeptService iEmpDeptService;

	@Autowired
	IFlowRecordService iFlowRecordService;

	@Autowired
	IStepRecordService iStepRecordService;

	@Autowired
	EmpMapper empMapper;
	
	@Autowired
	EmpDeptMapper empDeptMapper;
	
	@Autowired
	IStepService iStepService;

	@Autowired
	IJobService iJobService;
	/**
	 * key: "/emp/all", get 李绍圳
	 * 
	 * @param param
	 * @return
	 */
	public ResultInfo selectEmpByAll(JSONObject param) {
		String deptId = param.getString("deptId");
		String jobId = param.getString("jobId");
		String name = param.getString("name");
		String account = param.getString("account");
		QueryWrapper<EmpModel> em = new QueryWrapper<EmpModel>();
		if (StringUtils.hasLength(deptId)) {
			em.eq("dept.dept_id", deptId);
		}
		if (StringUtils.hasLength(jobId)) {
			em.eq("emp_dept.job_id", jobId);
		}
		if (StringUtils.hasLength(name)) {
			em.like("emp.name", name);
		}
		if (StringUtils.hasLength(account)) {
			em.like("account", account);
		}
		em.notIn("statu", "NPD","OUT");
		return ResultInfo.success(empMapper.selectEmpByAll(em));
	}

	/**
	 * key: "/emp/page", get 杨程
	 * 
	 * @param param
	 * @return
	 */
	public ResultInfo getEmpByPage(Integer current, Integer size, JSONObject param) {

		Integer deptId = param.getObject("deptId", Integer.class);
		Integer jobId = param.getObject("jobId", Integer.class);
		String name = param.getObject("name", String.class);
		String account = param.getObject("account", String.class);

		Page<EmpModel> page = new Page<EmpModel>(current, size);
		QueryWrapper<EmpModel> qw = new QueryWrapper<EmpModel>();

		if (StringUtils.hasLength(name)) {
			qw.like("e.name", name);
		}
		if (StringUtils.hasLength(account)) {
			qw.like("account", account);
		}
		if (deptId != null) {
			qw.eq("dept_id", deptId);
		}
		if (jobId != null) {
			qw.eq("job_id", jobId);
		}

		return ResultInfo.success(empMapper.getEmpPage(qw, page));
	}

	/**
	 * key: "/emp/info", get 王琪
	 * 
	 * @param param
	 * @return
	 */
	public ResultInfo getEmp(JSONObject param) {
    	Integer empId = param.getInteger("empId");
    	if(null == empId) {
    		throw new SystemException("1");
    	}
    	//通过empId查询emp表
    	Emp emp = iEmpService.getById(empId);
    	if(null == emp) {
    		throw new SystemException("2");
    	}
    	//通过emp里的userId查询user表
    	User user = iUserService.getById(emp.getUserId());
    	if(null == user) {
    		throw new SystemException("3");
    	}
    	//通过empId查询empDept表
    	QueryWrapper<EmpDept> empDeptQueryWrapper = new QueryWrapper<EmpDept>();
    	empDeptQueryWrapper.eq("emp_id", empId);
    	empDeptQueryWrapper.eq("a_flg", "1");
    	List<EmpDept> empDepts = iEmpDeptService.list(empDeptQueryWrapper);
    	if(0 == empDepts.size()) {
    		throw new SystemException("4");
    	}
    	//装到jsonObject对象返回给页面
    	JSONObject jsonObject = new JSONObject();
    	jsonObject.put("user", user);
    	jsonObject.put("emp", emp);
    	jsonObject.put("empDept", empDepts.get(0));
        return ResultInfo.success(jsonObject);
    }

	/**
	 * key: "/emp/info", post 王嘉曦
	 * 
	 * @param param
	 * @return
	 */
	@Transactional
	public synchronized ResultInfo newEmp(JSONObject param) {

		User user = param.getObject("user", User.class);

		if (null == user) {
			throw new SystemException("user对象为空");
		}
		
		if (!StringUtils.hasLength(user.getAccount())) {
			throw  new SystemException("账户名为空");
		}
		
		if (!StringUtils.hasLength(user.getTel())) {
			throw  new SystemException("手机号为空");
		}
		
		if (!StringUtils.hasLength(user.getRoles().replace("[", "").replace("]", ""))) {
			throw  new SystemException("角色为空");
		}
		
		QueryWrapper<User> accountQueryWrapper = new QueryWrapper<User>();
		accountQueryWrapper.eq("account", user.getAccount());
		long accountCount = iUserService.count(accountQueryWrapper.eq("account", user.getAccount()));
		if(0 < accountCount) {
			throw new SystemException("账户名已存在");
		}
		
		QueryWrapper<User> telQueryWrapper = new QueryWrapper<User>();
		telQueryWrapper.eq("tel", user.getTel());
		long telCount = iUserService.count(telQueryWrapper.eq("tel", user.getTel()));
		if (0 < telCount) {
			throw new SystemException("手机号已存在");
		}
		
		user.setSalt(StringGenerator.getSalt(5));
		user.setPassword(StringGenerator.eCodePassword("123456", user.getSalt()));
		iUserService.save(user);
		if (null == user.getUserId()) {
			throw new SystemException("user表存入失败");
		}
		
		
		
		Emp emp = param.getObject("emp", Emp.class);
		
		if (null == emp) {
			throw new SystemException("emp对象为空");
		}
		
		if(!StringUtils.hasLength(emp.getName())) {
			throw new SystemException("姓名为空");
		}
		
		emp.setUserId(user.getUserId());
		emp.setStatu("NDP");
		iEmpService.save(emp);
		if (null == emp.getEmpId()) {
			throw new SystemException("emp表存入失败");
		}
		
		
		
		EmpDept empDept = param.getObject("empDept", EmpDept.class);
		
		if(null == empDept.getDeptId()) {
			throw new SystemException("部门为空");
		}
		
		
		if (null == empDept.getJobId()) {
			throw new SystemException("职位为空");
		}
		
		empDept.setEmpId(emp.getEmpId());
		empDept.setAFlg(true);
        LocalDateTime currentDateTime = LocalDateTime.now();
        empDept.setSt(currentDateTime);
        empDept.setEt(null);
        iEmpDeptService.save(empDept);
        
        if (null == empDept.getEmpId() || null == empDept.getDeptId() || null == empDept.getJobId() ) {
			throw new SystemException("emp_dept表存入失败");
		}
        
        return ResultInfo.success("添加成功");
	}

	/**
	 * key: "/emp/info", put 姜东
	 * 
	 * @param param
	 * @return
	 */
	@Transactional
	public ResultInfo updateEmp(JSONObject param) {
		
		User user = param.getObject("user", User.class);
        /*取得传输的userId,判断该用户是否存在*/
        Integer id =  user.getUserId();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
        /* 构建查询条件，以user_id为条件。 */
        userQueryWrapper.eq("user_id", id);
        
        /* 查询用户 */
        List<User> users = iUserService.list(userQueryWrapper);
        
        /* 找不到记录时，抛异常 */
        if (null == users || users.size() == 0) {
            throw new SystemException("1");
        /* 找到多条记录时，抛异常 */
        } else if (users.size() > 1) {
            throw new SystemException("2");
        }

        /* 找且只找到一条时，调出对象信息。 */
        User userParam = users.get(0);
        
        /*修改账号*/
        String account = user.getAccount();
        String tel = user.getTel();
        
        if(account == null) {
        	 throw new SystemException("5");
        }
        
        userQueryWrapper.clear();
        userQueryWrapper.eq("account", account);
        long accountCount = iUserService.count(userQueryWrapper);
		
		if(1 < accountCount) {
			throw new SystemException("11");
		}
        
        userParam.setAccount(account);
        
        /*修改手机号*/
        
        
        if(tel == null) {
        	 throw new SystemException("6");
        }
        
        userQueryWrapper.clear();
        userQueryWrapper.eq("tel", tel);
        long telCount = iUserService.count(userQueryWrapper);
		
		if(1 < telCount) {
			throw new SystemException("12");
		}
        
        userParam.setTel(tel);
        
//        /*修改密码*/
//        /*获取输入的旧密码*/
//        String password = userModel.getPassword();
//        /*将获取的旧密码进行加盐，加密处理*/
//        String ecodePassword = StringGenerator.eCodePassword(password,userParam.getSalt());	
//        /*将加密后的密码与数据库中的密码进行比较,不相等，抛出异常*/
//        if (!ecodePassword.equals(userParam.getPassword())) {
//            throw new SystemException("3");
//        }
//        
//        String newPassword = userModel.getNewPassword();
//        
//        if(newPassword == null) {
//        	 throw new SystemException("4");
//        }
//        
//        userParam.setPassword(newPassword);
        iUserService.updateById(userParam);
        
        Emp emp = param.getObject("emp", Emp.class);
        /*取得传输的empId,判断该用户是否存在*/
        Integer empId =  emp.getEmpId();
        System.out.println(empId);
        QueryWrapper<Emp> empQueryWrapper = new QueryWrapper<Emp>();
        /* 构建查询条件，以user_id为条件。 */
        empQueryWrapper.eq("emp_id", empId);
        
        /* 查询用户 */
        List<Emp> emps = iEmpService.list(empQueryWrapper);
        
        /* 找不到记录时，抛异常 */
        if (null == emps || emps.size() == 0) {
            throw new SystemException("7");
        /* 找到多条记录时，抛异常 */
        } else if (emps.size() > 1) {
            throw new SystemException("8");
        }

        /* 找且只找到一条时，调出对象信息。 */
        Emp empParam = emps.get(0);
        
        /*修改员工名称*/
        String name = emp.getName();
        
        if(name == null) {
        	 throw new SystemException("9");
        }
        
        empParam.setName(name);
        
  
        
//        /*修改员工状态*/
//        String statu = emp.getStatu();
//        
//        if(statu == null) {
//        	 throw new SystemException("10");
//        }
//        
//        empParam.setStatu(statu);
        
        iEmpService.updateById(empParam);  
        
        return ResultInfo.success("修改成功");
	}

	/**
	 * key: "/emp/info", delete 姜东
	 * 
	 * @param empId
	 * @return
	 */
	public ResultInfo deleteEmp(Integer empId) {
		QueryWrapper<Emp> empQueryWrapper = new QueryWrapper<Emp>();
        /* 构建查询条件，以user_id为条件。 */
        empQueryWrapper.eq("emp_id", empId);
        
        /* 查询用户 */
        List<Emp> emps = iEmpService.list(empQueryWrapper);
        
        /* 找不到记录时，抛异常 */
        if (null == emps || emps.size() == 0) {
            throw new SystemException("1");
        /* 找到多条记录时，抛异常 */
        } else if (emps.size() > 1) {
            throw new SystemException("2");
        }

        /* 找且只找到一条时，调出对象信息。 */
        Emp empParam = emps.get(0);
        
        empParam.setStatu("OUT");
        
        iEmpService.updateById(empParam);
    	
//    	Integer userId = empParam.getUserId();
//    	
//    	iEmpService.removeById(empId);
//    	
//    	QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
//        /* 构建查询条件，以user_id为条件。 */
//    	userQueryWrapper.eq("user_id", userId);
//        
//        /* 查询用户 */
//        List<User> users = iUserService.list(userQueryWrapper);
//        
//        /* 找不到记录时，抛异常 */
//        if (null == users || users.size() == 0) {
//            throw new SystemException("3");
//        /* 找到多条记录时，抛异常 */
//        } else if (users.size() > 1) {
//            throw new SystemException("4");
//        }
//    	
//    	iUserService.removeById(userId);
    	
        return ResultInfo.success("删除成功");
	}

	/**
	 * key: "/emp/dept/page", get 丛佩东
	 * 
	 * @param current
	 * @param size
	 * @param param
	 * @return
	 */
	public ResultInfo getDeptOfEmpByPage(Integer current, Integer size, JSONObject param) {
	 	Integer empId = param.getInteger("empId");
    	if (null == empId) {
			throw new SystemException("1");
		}
    	QueryWrapper<EmpDept> queryWrapper = new QueryWrapper<EmpDept>();
    	queryWrapper.eq("emp_dept.emp_id", empId);
    	IPage<EmpDeptModel> deptOfEmpByPage = empDeptMapper.getDeptOfEmpByPage(new Page<>(current, size),queryWrapper);
        return ResultInfo.success(deptOfEmpByPage);
	}

	/**
	 * key: "/emp/flow/record/page", get 丛佩东
	 * 
	 * @param current
	 * @param size
	 * @param param
	 * @return
	 */
	public ResultInfo getFlowRecordByPage(Integer current, Integer size, JSONObject param) {
        Integer empId = param.getInteger("empId");
        if (null == empId) {
			throw new SystemException("1");
		}
        QueryWrapper<FlowRecord> queryWrapper = new QueryWrapper<>();
        if (null != empId) {
        	queryWrapper.eq("flow_record.emp_id", empId);
        }
        IPage<FlowRecord> pageInfo = new Page<FlowRecord>(current, size);
    	return ResultInfo.success(iFlowRecordService.page(pageInfo, queryWrapper));
	}

	/**
	 * key: "/emp/flow/record/info", get 丛佩东
	 * 
	 * @param flRId
	 * @return
	 */
	public ResultInfo getFlowReocrd(Integer flRId) {
		if (null == flRId) {
    		throw new SystemException("1");
		}
		QueryWrapper<FlowRecord> fQueryWrapper = new QueryWrapper<>();
    	fQueryWrapper.eq("flow_record.fl_r_id", flRId);
    	List<FlowRecord> flowRecordList = iFlowRecordService.list(fQueryWrapper);
    	if(null == flowRecordList && 0 == flowRecordList.size()) {
    		throw new SystemException("2");
    	}
    	FlowRecord flowRecord = flowRecordList.get(0);
		QueryWrapper<StepRecord> sQueryWrapper = new QueryWrapper<>();
		sQueryWrapper.eq("step_record.fl_r_id", flRId);
		List<StepRecord> stepRecordList = iStepRecordService.list(sQueryWrapper);
		if(null == stepRecordList && 0 == stepRecordList.size()) {
    		throw new SystemException("3");
    	}
		StepRecord[] stepRecordArray = stepRecordList.toArray(new StepRecord[stepRecordList.size()]);
		
		JSONObject param = new JSONObject();
		param.put("flowRecord", flowRecord);
		param.put("stepRecord", stepRecordArray);
        return ResultInfo.success(param);
	}

	/**
	 * key: "/emp/flow/record/info", post 杨程
	 * 
	 * @param
	 * @return
	 */
	public synchronized ResultInfo getFlowReocrd(JSONObject param) {
		  FlowRecord flowRecord = param.getObject("flowRecord", FlowRecord.class);
		  String stepRecords = param.getObject("stepRecords", String.class);
		  List<StepRecord> stepRecordList = JSON.parseArray(stepRecords,StepRecord.class);
		  
		  if(flowRecord.getName()==null) {
		   throw new SystemException("1");
		  }
		  if(flowRecord.getEmpId()==null) {
		   throw new SystemException("2");
		  }
		  if(flowRecord.getDeptId()==null) {
		   throw new SystemException("3");
		  }
		  if(flowRecord.getFlowId()==null) {
		   throw new SystemException("4");
		  }
		  if(flowRecord.getSt()==null) {
		   throw new SystemException("5");
		  }
		  if(flowRecord.getEt()==null) {
		   throw new SystemException("6");
		  }
		  boolean saveFlowRecord = iFlowRecordService.save(flowRecord);
		  if (!saveFlowRecord) {
	            throw new SystemException ("保存请假记录失败！");
	        }
		  QueryWrapper<FlowRecord> queryWrapper = new QueryWrapper<FlowRecord>();
		  queryWrapper.eq("name", flowRecord.getName());
		  queryWrapper.eq("emp_id", flowRecord.getEmpId());
		  queryWrapper.eq("dept_id", flowRecord.getDeptId());
		  queryWrapper.eq("flow_id", flowRecord.getFlowId());
		  queryWrapper.eq("st", flowRecord.getSt());
		  queryWrapper.eq("et", flowRecord.getEt());
		  List<FlowRecord> flowRecords = iFlowRecordService.list(queryWrapper);
		  if(flowRecords.size() == 0 || flowRecords.size() > 1) {
			  throw new SystemException("7");
		  }
		  
		  
		  for (int index = 0; index < stepRecordList.size(); index++) {
			  stepRecordList.get(index).setFlRId(flowRecords.get(0).getFlowId());
			  
			  //找到当前记录的step_id-->job_id-->dept_id-->dept_emp---emp_id
			  QueryWrapper<Step> stepQueryWrapper = new QueryWrapper<Step>();
			  stepQueryWrapper.eq("step_id", stepRecordList.get(index).getStepId());
			  List<Step> stepList = iStepService.list(stepQueryWrapper);
			  if(stepList.size() == 0 || stepList.size() > 1) {
				  throw new SystemException("8");
			  }
			 
			  QueryWrapper<Job> jobQueryWrapper = new QueryWrapper<Job>();
			  jobQueryWrapper.eq("job_id", stepList.get(0).getJobId());
			  List<Job> jobList = iJobService.list(jobQueryWrapper);
			  if(jobList.size() == 0 || jobList.size() > 1) {
				  throw new SystemException("9");
			  }
			  
			  QueryWrapper<EmpDept> empDeptQueryWrapper = new QueryWrapper<EmpDept>();
			  empDeptQueryWrapper.eq("dept_id", jobList.get(0).getDeptId());
			  empDeptQueryWrapper.eq("job_id", jobList.get(0).getDeptId());
			  List<EmpDept> empDeptList = iEmpDeptService.list(empDeptQueryWrapper);
			  if(empDeptList.size() == 0 || empDeptList.size() > 1) {
				  throw new SystemException("10");
			  }
				// 将当前的empdept的emp_id插入到step_record的ap_emp_id
			  
		  }
		  
		  
		  
		  
		  return ResultInfo.success("成功");
		 
	}

	/**
	 * key: "/emp/qiandao/all", get
	 * 
	 * @param param
	 * @return
	 */
	public ResultInfo getQiandaoByAll(JSONObject param) {
		return ResultInfo.success();
	}

}
